package com.ruoyi.common.utils.modbus;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TcpToSerialServer {
    private static final Log log = LogFactory.getLog(TcpToSerialServer.class);
    private static final int DEFAULT_PORT = 18888; // 默认监听端口

    private static ServerSocket serverSocket;

    public static void main(String[] args) {
//        String receivedData = startServer(DEFAULT_PORT, "测试");
//        System.out.println("接收数据：" + receivedData);
        for (int i = 0; i < 10; i++) {
            System.out.println(sendData(DEFAULT_PORT, i + "cs"));
        }
    }


    public static String sendData(int serverPort, String dataToSend) {
        String responseData = null;

        try {
            if (serverSocket == null) {
                // 建立TCP连接
                serverSocket = new ServerSocket(serverPort);
            } else {
                int port = serverSocket.getLocalPort(); // 获取实际监听的端口
                if (port != serverPort) {
                    serverSocket.close();
                    // 建立TCP连接
                    serverSocket = new ServerSocket(serverPort);
                }
            }
            // 等待客户端连接
            Socket socket = serverSocket.accept();
            // 获取输出流
            OutputStream outputStream = socket.getOutputStream();
            // 添加ASCII码换行符 (通常是 \r\n 或 \n)
            // 1. 使用标准的ASCII换行符 (推荐)
            String messageWithNewline = dataToSend + "\r\n";
            // 发送数据到服务器
            outputStream.write(messageWithNewline.getBytes(StandardCharsets.UTF_8));
            // 确保数据立即发送
            outputStream.flush();
            // 接收服务器的响应数据 (如果需要)
            InputStream inputStream = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = inputStream.read(buffer);
            if (bytesRead > 0) {
                responseData = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
            }
            // 关闭连接
            socket.close();
        } catch (IOException e) {
            log.error("【dataUpload】【0183】输出异常 : " + e.getMessage());
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException ex) {
                log.error("【dataUpload】【0183】输出异常 : " + ex.getMessage());
            }
        }
        return responseData;
    }


    /**
     * 启动TCP服务端
     *
     * @param port 监听的端口号
     */
    public static String startServer(int port, String dataToSend) {
        String receivedData = "";
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            log.info("【Server】Started, listening on port: " + port);

            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
//                log.info("【Server】Client connected: " + clientSocket.getInetAddress());

                // 处理客户端请求（新线程避免阻塞）
                receivedData = handleClient(clientSocket, dataToSend);
//                new Thread(() -> {
//                    receivedData.set(handleClient(clientSocket, dataToSend));
//                }).start();
            }
        } catch (IOException e) {
            log.error("【Server】Error: " + e.getMessage());
        }
        return receivedData;
    }

    /**
     * 处理客户端连接
     *
     * @param clientSocket 客户端Socket对象
     */
    private static String handleClient(Socket clientSocket, String dataToSend) {
        String receivedData = null;
        try (
                InputStream inputStream = clientSocket.getInputStream();
                OutputStream outputStream = clientSocket.getOutputStream()
        ) {
            // 1. 接收客户端数据
            byte[] buffer = new byte[1024];
            int bytesRead = inputStream.read(buffer);
            if (bytesRead > 0) {
                receivedData = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
                log.info("【Server】Received data: " + receivedData.trim()); // trim() 去除换行符

                // 2. 模拟处理数据（示例：原样返回 + "ACK"）
                String response = dataToSend.trim() + "\r\n";
                outputStream.write(response.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
//                log.info("【Server】Sent response: " + response.trim());
            }
        } catch (IOException e) {
            log.error("【Server】Client handling error: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                log.error("【Server】Failed to close client socket: " + e.getMessage());
            }
        }
        return receivedData;
    }
}
